package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
	"work-chess/dao"
	"work-chess/router/hub"
)

func ChessConn() gin.HandlerFunc {
	return func(con *gin.Context) {
		c := new(Context)
		c.Context = con
		fmt.Println("/ws")
		userName := c.Query("username")
		password := c.Query("password")
		fmt.Println("userName= ", userName)
		_, passwd, err := dao.SelectUserName(userName)
		fmt.Println("pw = ", passwd)
		if err == nil && passwd == password {
			log.Println("登录游戏成功")
		} else {
			c.ReturnMessage(400, "登录失败")
			return
		}
		group := c.Query("group")
		if group == "" {
			c.ReturnMessage(201, "No Group Setting")
			return
		}
		//upgrader用于在升级时让websocket包获取请求的信息，并在执行Upgrade方法验证这个websocket连接是否合法
		upgrader := websocket.Upgrader{
			Subprotocols: []string{c.GetHeader("Sec-WebSocket-Protocol")},
			CheckOrigin: func(r *http.Request) bool {
				return true
			}}

		conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
		//返回了错误多半是个不合法的连接
		g, err := strconv.Atoi(group)
		if err != nil {
			c.ReturnMessage(500, "访问格式不正确")
			return
		}
		connection := hub.Center.AddIntoGroup(userName, g, conn)

		fmt.Println("得到一个新连接")
		go connection.Receive()
		go connection.Send()
	}
}
